package com.lnn.springBase;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.PriorityQueue;
import java.util.stream.Collectors;

public class Top100Finder {

    public static void main(String[] args) {
        int[] data = generateData(100000);
        List<Integer> top100 = findTop100(data);
        // 输出最大前 100 个数
        for (int num : top100) {
            System.out.println(num);
        }
    }

    public static List<Integer> findTop100(int[] data) {
        PriorityQueue<Integer> minHeap = new PriorityQueue<>(Comparator.reverseOrder());
        //1.填充初始堆
        for (int i=0;i<10;i++) {
            minHeap.add(data[i]);
        }
        //2.遍历剩余元素
        for (int i=10;i<data.length;i++) {
            if (data[i] < minHeap.peek()) {
                minHeap.poll();
                minHeap.add(data[i]);
            }
        }
        return new ArrayList<>(minHeap).stream().sorted(Comparator.naturalOrder()).collect(Collectors.toList());
    }

    private static int[] generateData(int size) {
        int[] data = new int[size];
        for (int i = 0; i < size; i++) {
            data[i] = (int) (Math.random() * 100000000);
        }
        return data;
    }
}
